<template>
  <div class="game-3d-character">
    <div ref="threeContainer" class="three-container"></div>
  </div>
</template>

<script>
import * as THREE from 'three'
import { markRaw } from 'vue'

export default {
  name: 'Game3DCharacter',
  props: {
    timeLeft: {
      type: Number,
      required: true
    },
    gameStarted: {
      type: Boolean,
      default: false
    },
    gameOver: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      // 使用markRaw防止Three.js对象被Vue响应式系统代理
      threeObjects: markRaw({
        scene: null,
        camera: null,
        renderer: null,
        character: null,
        signBoard: null,
        textTexture: null,
        textCanvas: null,
        textMaterial: null
      }),
      animationId: null,
      isDestroyed: false
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.initThreeJS()
      this.createCharacter()
      this.createSignBoard()
      this.updateSignText(this.timeLeft)
      this.animate()
    })
  },
  beforeUnmount() {
    this.cleanup()
  },
  watch: {
    timeLeft: {
      handler(newTime) {
        if (!this.isDestroyed) {
          this.updateSignText(newTime)
        }
      },
      immediate: true
    }
  },
  methods: {
    initThreeJS() {
      try {
        // 创建场景
        this.threeObjects.scene = new THREE.Scene()
        this.threeObjects.scene.background = new THREE.Color(0xf0f8ff)

        // 创建相机
        this.threeObjects.camera = new THREE.PerspectiveCamera(
          75,
          200 / 300,
          0.1,
          1000
        )
        this.threeObjects.camera.position.set(0, 1, 6)
        this.threeObjects.camera.lookAt(0, 0, 0)

        // 创建渲染器
        this.threeObjects.renderer = new THREE.WebGLRenderer({ 
          antialias: true,
          alpha: true
        })
        this.threeObjects.renderer.setSize(200, 300)
        this.threeObjects.renderer.setPixelRatio(window.devicePixelRatio)
        
        // 添加到DOM
        if (this.$refs.threeContainer) {
          this.$refs.threeContainer.appendChild(this.threeObjects.renderer.domElement)
        }

        // 添加光源
        const ambientLight = new THREE.AmbientLight(0xffffff, 0.6)
        this.threeObjects.scene.add(ambientLight)

        const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8)
        directionalLight.position.set(5, 10, 5)
        this.threeObjects.scene.add(directionalLight)

        // 添加点光源增强效果
        const pointLight = new THREE.PointLight(0xffffff, 0.5, 100)
        pointLight.position.set(0, 5, 5)
        this.threeObjects.scene.add(pointLight)
      } catch (error) {
        console.error('Three.js initialization error:', error)
      }
    },

    createCharacter() {
      try {
        const characterGroup = new THREE.Group()

        // 头部 - 更大更圆润
        const headGeometry = new THREE.SphereGeometry(0.5, 32, 32)
        const headMaterial = new THREE.MeshPhongMaterial({ 
          color: 0xffdbac,
          shininess: 30
        })
        const head = new THREE.Mesh(headGeometry, headMaterial)
        head.position.y = 1.8
        characterGroup.add(head)

        // 眼睛
        const eyeGeometry = new THREE.SphereGeometry(0.08, 16, 16)
        const eyeMaterial = new THREE.MeshPhongMaterial({ color: 0x000000 })
        
        const leftEye = new THREE.Mesh(eyeGeometry, eyeMaterial)
        leftEye.position.set(-0.15, 1.9, 0.35)
        characterGroup.add(leftEye)
        
        const rightEye = new THREE.Mesh(eyeGeometry, eyeMaterial)
        rightEye.position.set(0.15, 1.9, 0.35)
        characterGroup.add(rightEye)

        // 眼睛高光
        const highlightGeometry = new THREE.SphereGeometry(0.03, 8, 8)
        const highlightMaterial = new THREE.MeshPhongMaterial({ color: 0xffffff })
        
        const leftHighlight = new THREE.Mesh(highlightGeometry, highlightMaterial)
        leftHighlight.position.set(-0.12, 1.95, 0.4)
        characterGroup.add(leftHighlight)
        
        const rightHighlight = new THREE.Mesh(highlightGeometry, highlightMaterial)
        rightHighlight.position.set(0.18, 1.95, 0.4)
        characterGroup.add(rightHighlight)

        // 嘴巴 - 微笑
        const mouthGeometry = new THREE.TorusGeometry(0.08, 0.02, 8, 16, Math.PI)
        const mouthMaterial = new THREE.MeshPhongMaterial({ color: 0xff6b6b })
        const mouth = new THREE.Mesh(mouthGeometry, mouthMaterial)
        mouth.position.set(0, 1.6, 0.35)
        mouth.rotation.z = Math.PI
        characterGroup.add(mouth)

        // 脸颊红晕
        const cheekGeometry = new THREE.SphereGeometry(0.08, 16, 16)
        const cheekMaterial = new THREE.MeshPhongMaterial({ 
          color: 0xff9999,
          transparent: true,
          opacity: 0.6
        })
        
        const leftCheek = new THREE.Mesh(cheekGeometry, cheekMaterial)
        leftCheek.position.set(-0.3, 1.7, 0.3)
        characterGroup.add(leftCheek)
        
        const rightCheek = new THREE.Mesh(cheekGeometry, cheekMaterial)
        rightCheek.position.set(0.3, 1.7, 0.3)
        characterGroup.add(rightCheek)

        // 身体 - 更可爱的形状
        const bodyGeometry = new THREE.CapsuleGeometry(0.4, 0.8, 4, 8)
        const bodyMaterial = new THREE.MeshPhongMaterial({ 
          color: 0x4a90e2,
          shininess: 50
        })
        const body = new THREE.Mesh(bodyGeometry, bodyMaterial)
        body.position.y = 0.8
        characterGroup.add(body)

        // 手臂 - 更自然的形状
        const armGeometry = new THREE.CapsuleGeometry(0.08, 0.6, 4, 8)
        const armMaterial = new THREE.MeshPhongMaterial({ color: 0xffdbac })
        
        const leftArm = new THREE.Mesh(armGeometry, armMaterial)
        leftArm.position.set(-0.5, 1, 0)
        leftArm.rotation.z = Math.PI / 6
        characterGroup.add(leftArm)

        // 右臂（举牌子）
        const rightArm = new THREE.Mesh(armGeometry, armMaterial)
        rightArm.position.set(0.5, 1.2, 0)
        rightArm.rotation.z = -Math.PI / 4
        characterGroup.add(rightArm)

        // 手掌
        const handGeometry = new THREE.SphereGeometry(0.12, 16, 16)
        const handMaterial = new THREE.MeshPhongMaterial({ color: 0xffdbac })
        
        const leftHand = new THREE.Mesh(handGeometry, handMaterial)
        leftHand.position.set(-0.7, 0.7, 0)
        characterGroup.add(leftHand)
        
        const rightHand = new THREE.Mesh(handGeometry, handMaterial)
        rightHand.position.set(0.8, 1.5, 0)
        characterGroup.add(rightHand)

        // 腿部
        const legGeometry = new THREE.CapsuleGeometry(0.1, 0.6, 4, 8)
        const legMaterial = new THREE.MeshPhongMaterial({ color: 0x2c3e50 })
        
        const leftLeg = new THREE.Mesh(legGeometry, legMaterial)
        leftLeg.position.set(-0.15, 0, 0)
        characterGroup.add(leftLeg)

        const rightLeg = new THREE.Mesh(legGeometry, legMaterial)
        rightLeg.position.set(0.15, 0, 0)
        characterGroup.add(rightLeg)

        // 脚
        const footGeometry = new THREE.CapsuleGeometry(0.12, 0.2, 4, 8)
        const footMaterial = new THREE.MeshPhongMaterial({ color: 0x8b4513 })
        
        const leftFoot = new THREE.Mesh(footGeometry, footMaterial)
        leftFoot.position.set(-0.15, -0.4, 0.1)
        leftFoot.rotation.x = Math.PI / 2
        characterGroup.add(leftFoot)

        const rightFoot = new THREE.Mesh(footGeometry, footMaterial)
        rightFoot.position.set(0.15, -0.4, 0.1)
        rightFoot.rotation.x = Math.PI / 2
        characterGroup.add(rightFoot)

        characterGroup.position.set(-1.5, 0, 0)
        this.threeObjects.character = characterGroup
        this.threeObjects.scene.add(characterGroup)
      } catch (error) {
        console.error('Character creation error:', error)
      }
    },

    createSignBoard() {
      try {
        // 牌子支架
        const poleGeometry = new THREE.CylinderGeometry(0.03, 0.03, 1.5, 8)
        const poleMaterial = new THREE.MeshPhongMaterial({ 
          color: 0x8b4513,
          shininess: 20
        })
        const pole = new THREE.Mesh(poleGeometry, poleMaterial)
        pole.position.set(1.2, 0.75, 0)

        // 牌子板面 - 更大更清晰
        const boardGeometry = new THREE.PlaneGeometry(2, 1.2)
        
        // 创建超高分辨率画布
        this.threeObjects.textCanvas = document.createElement('canvas')
        this.threeObjects.textCanvas.width = 800  // 更高分辨率
        this.threeObjects.textCanvas.height = 600
        
        const context = this.threeObjects.textCanvas.getContext('2d')
        
        // 创建纹理
        this.threeObjects.textTexture = new THREE.CanvasTexture(this.threeObjects.textCanvas)
        this.threeObjects.textTexture.minFilter = THREE.LinearFilter
        this.threeObjects.textTexture.magFilter = THREE.LinearFilter
        
        this.threeObjects.textMaterial = new THREE.MeshPhongMaterial({ 
          map: this.threeObjects.textTexture,
          transparent: true,
          shininess: 100
        })
        
        const board = new THREE.Mesh(boardGeometry, this.threeObjects.textMaterial)
        board.position.set(1.2, 1.8, 0)

        this.threeObjects.signBoard = new THREE.Group()
        this.threeObjects.signBoard.add(pole)
        this.threeObjects.signBoard.add(board)
        
        this.threeObjects.scene.add(this.threeObjects.signBoard)
      } catch (error) {
        console.error('Sign board creation error:', error)
      }
    },

    updateSignText(timeLeft) {
      if (!this.threeObjects.textCanvas || this.isDestroyed) return

      try {
        const canvas = this.threeObjects.textCanvas
        const context = canvas.getContext('2d')
        
        // 清除画布
        context.clearRect(0, 0, canvas.width, canvas.height)
        
        // 绘制背景渐变
        const gradient = context.createLinearGradient(0, 0, 0, canvas.height)
        gradient.addColorStop(0, '#ffffff')
        gradient.addColorStop(0.5, '#f8f9fa')
        gradient.addColorStop(1, '#e9ecef')
        context.fillStyle = gradient
        context.fillRect(0, 0, canvas.width, canvas.height)
        
        // 绘制装饰边框
        context.strokeStyle = '#007bff'
        context.lineWidth = 12
        context.strokeRect(6, 6, canvas.width - 12, canvas.height - 12)
        
        // 内边框
        context.strokeStyle = '#ffffff'
        context.lineWidth = 6
        context.strokeRect(18, 18, canvas.width - 36, canvas.height - 36)
        
        // 设置文字样式
        context.textAlign = 'center'
        context.textBaseline = 'middle'
        
        // 标题文字 - 更大更清晰
        context.fillStyle = '#343a40'
        context.font = 'bold 56px "Microsoft YaHei", Arial, sans-serif'
        context.strokeStyle = '#ffffff'
        context.lineWidth = 4
        context.strokeText('剩余时间', canvas.width / 2, 120)
        context.fillText('剩余时间', canvas.width / 2, 120)
        
        // 时间文字 - 超大字体
        const timeText = `${timeLeft}秒`
        context.fillStyle = timeLeft <= 10 ? '#dc3545' : '#007bff'
        context.font = 'bold 120px "Microsoft YaHei", Arial, sans-serif'
        
        // 添加强烈的文字阴影
        context.shadowColor = 'rgba(0, 0, 0, 0.5)'
        context.shadowOffsetX = 6
        context.shadowOffsetY = 6
        context.shadowBlur = 10
        
        // 白色描边
        context.strokeStyle = '#ffffff'
        context.lineWidth = 8
        context.strokeText(timeText, canvas.width / 2, 300)
        context.fillText(timeText, canvas.width / 2, 300)
        
        // 清除阴影
        context.shadowColor = 'transparent'
        context.shadowOffsetX = 0
        context.shadowOffsetY = 0
        context.shadowBlur = 0
        
        // 状态文字 - 更大更醒目
        let statusText = ''
        let statusColor = ''
        if (!this.gameStarted) {
          statusText = '🎮 点击开始'
          statusColor = '#28a745'
        } else if (this.gameOver) {
          statusText = '🎯 游戏结束'
          statusColor = '#dc3545'
        } else if (timeLeft <= 10) {
          statusText = '⚡ 时间紧急!'
          statusColor = '#dc3545'
        } else {
          statusText = '💪 加油!'
          statusColor = '#28a745'
        }
        
        context.fillStyle = statusColor
        context.font = 'bold 48px "Microsoft YaHei", Arial, sans-serif'
        context.strokeStyle = '#ffffff'
        context.lineWidth = 4
        context.strokeText(statusText, canvas.width / 2, 480)
        context.fillText(statusText, canvas.width / 2, 480)
        
        // 添加装饰元素
        if (timeLeft <= 10 && this.gameStarted && !this.gameOver) {
          // 紧急状态的闪烁效果
          const flash = Math.sin(Date.now() * 0.01) > 0
          if (flash) {
            context.fillStyle = 'rgba(220, 53, 69, 0.2)'
            context.fillRect(0, 0, canvas.width, canvas.height)
          }
        }
        
        // 更新纹理
        if (this.threeObjects.textTexture) {
          this.threeObjects.textTexture.needsUpdate = true
        }
      } catch (error) {
        console.error('Text update error:', error)
      }
    },

    animate() {
      if (this.isDestroyed) return

      try {
        this.animationId = requestAnimationFrame(() => this.animate())
        
        // 更生动的动画
        if (this.threeObjects.character && this.threeObjects.signBoard) {
          const time = Date.now() * 0.001
          
          // 小人轻微摇摆
          this.threeObjects.character.rotation.y = Math.sin(time * 0.8) * 0.1
          this.threeObjects.character.position.y = Math.sin(time * 1.2) * 0.05
          
          // 牌子摇摆
          this.threeObjects.signBoard.rotation.z = Math.sin(time * 0.6) * 0.05
          
          // 紧急状态下的快速摇摆
          if (this.timeLeft <= 10 && this.gameStarted && !this.gameOver) {
            this.threeObjects.character.rotation.y += Math.sin(time * 3) * 0.02
            this.threeObjects.signBoard.rotation.z += Math.sin(time * 4) * 0.02
          }
        }
        
        if (this.threeObjects.renderer && this.threeObjects.scene && this.threeObjects.camera) {
          this.threeObjects.renderer.render(this.threeObjects.scene, this.threeObjects.camera)
        }
      } catch (error) {
        console.error('Animation error:', error)
      }
    },

    cleanup() {
      this.isDestroyed = true
      
      if (this.animationId) {
        cancelAnimationFrame(this.animationId)
        this.animationId = null
      }

      // 清理Three.js资源
      if (this.threeObjects.renderer) {
        this.threeObjects.renderer.dispose()
        if (this.$refs.threeContainer && this.threeObjects.renderer.domElement) {
          this.$refs.threeContainer.removeChild(this.threeObjects.renderer.domElement)
        }
      }

      // 清理纹理
      if (this.threeObjects.textTexture) {
        this.threeObjects.textTexture.dispose()
      }
    }
  }
}
</script>

<style scoped>
.game-3d-character {
  position: fixed;
  top: 20px;
  right: 20px;
  width: 200px;
  height: 300px;
  z-index: 100;
  border-radius: 15px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.15);
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  overflow: hidden;
  border: 3px solid #ffffff;
}

.three-container {
  width: 100%;
  height: 100%;
}

.three-container canvas {
  border-radius: 12px;
}
</style> 